package com.turing.post.account.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.account.util.MasterAccount;
import com.turing.post.account.util.MasterAccountDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

@Stateless(mappedName = "account.impl.MasterAccountDaoImpl")
@Remote
@Local
public class MasterAccountDaoImpl implements MasterAccountDao {
	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	/**
	 * 插入主帐户记录
	 */
	public void insert(MasterAccount mac) throws PCPSApplicationException {
		GeneralDao.insert(_em, mac);
	}

	/**
	 * 更新主帐户记录
	 * 
	 * @param mac
	 * @throws PCPSApplicationException
	 */
	public void update(MasterAccount mac) throws PCPSApplicationException {
		GeneralDao.update(_em, mac);
	}

	/**
	 * 根据主帐号号检索主帐户
	 */
	public MasterAccount getMasterAccountByMasterAccNo(BigInteger masterAccNo) {
		//PCPSUtil.Log("getMasterAccountByMasterAccNo(" + masterAccNo.toString()
		//		+ ") called!");
		return _em.find(MasterAccount.class, masterAccNo);
	}

	/**
	 * 记录锁定,准备更新
	 * 
	 * @param masterAccNo
	 */
	@SuppressWarnings("unchecked")
	public MasterAccount getMasterAccountByMasterAccNoForUpdate(
			BigInteger masterAccNo) {
		Query query = _em
				.createNativeQuery(
						"select t.* from MasterAccount t where t.masterAccNo = ?1 for update",
						MasterAccount.class);
		query.setParameter(1, masterAccNo);
		List<MasterAccount> macc = query.getResultList();
		if (macc == null || macc.size() != 1)
			return null;
		MasterAccount ma = macc.get(0);
		_em.refresh(ma);
		return getMasterAccountByMasterAccNo(ma.getMasterAccNo());
	}

	/**
	 * 置空卡号
	 * 
	 * @param masterAccNo
	 */
	public void clearCardNo(BigInteger masterAccNo) {
		Query query = _em
				.createNativeQuery("update MasterAccount t set t.cardNo = null where t.masterAccNo = ?1");
		query.setParameter(1, masterAccNo);
		query.executeUpdate();
	}

	@Override
	public MasterAccount getMasterAccountByCardNo(String cardno) {
		Query query = _em.createNativeQuery(
				"select * from MasterAccount t where t.cardNo =?1",
				MasterAccount.class);
		query.setParameter(1, cardno);
		if (query.getSingleResult() != null) {
			return (MasterAccount) query.getSingleResult();
		}
		return null;
	}
}
